<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleDownload"
        >下载</el-button>
      </el-col>
      <el-col :span="3">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入搜索关键词"
          clearable
        />
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleSearch"
        >搜索</el-button>
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="newList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        label="杆号序号"
        prop="ganhaoid"
        sortable="custom"
        @sort-change="handleSort('ganhaoid')"
      />
      <el-table-column
        label="杆号"
        prop="ganhaoname"
        sortable="custom"
        @sort-change="handleSort('ganhaoname')"
      />
      <el-table-column
        label="工区ID"
        prop="gqid"
        sortable="custom"
        @sort-change="handleSort('gqid')"
      />
      <!-- <el-table-column
        label="工区ID"
        prop="gq_id"
        sortable="custom"
        @sort-change="handleSort('gq_id')"
      /> -->
      <el-table-column label="工区名称" prop="gongquName" />
      <el-table-column
        label="站区ID"
        prop="zhanquid"
        sortable="custom"
        @sort-change="handleSort('zhanquid')"
      />
      <!-- <el-table-column
        label="站区ID"
        prop="zhanqu_id"
        sortable="custom"
        @sort-change="handleSort('zhanqu_id')"
      /> -->
      <el-table-column label="站区名称" prop="zaname" />
      <el-table-column label="隧道编号" prop="sdid" />
      <el-table-column label="隧道名称" prop="sdname" />
      <!--       <el-table-column label="隧道编号" prop="sd_id" />
      <el-table-column label="隧道名称" prop="sd_name" /> -->
      <el-table-column label="支柱型号" prop="zztype" />
      <el-table-column label="负责人" prop="directors" />
      <el-table-column label="公里标" prop="gonglibiao" />
      <el-table-column label="跨距" prop="kuaju" />
      <el-table-column label="概述" prop="overview" />
      <el-table-column label="备注" prop="remark" />

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button size="mini" type="text" @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page.sync="currentPage"
      :page-sizes="[5, 10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="editDialogVisible"
      width="30%"
      @close="handleDialogClose"
    >
      <el-form :model="addForm">
        <el-row>
          <el-col :span="12">
            <el-form-item label="杆号序号" label-width="100px">
              <el-input
                v-model="addForm.ganhaoid"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item label="杆号" label-width="100px">
              <el-input
                v-model="addForm.ganhaoname"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工区ID" label-width="100px">
              <el-input v-model="addForm.gqid" autocomplete="off"></el-input>
              <!-- <el-input v-model="addForm.gq_id" autocomplete="off"></el-input> -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="站区ID" label-width="100px">
              <el-input
                v-model="addForm.zhanquid"
                autocomplete="off"
              ></el-input>
              <!-- <el-input
                v-model="addForm.zhanqu_id"
                autocomplete="off"
              ></el-input> -->
            </el-form-item>
            <el-form-item label="站区名称" label-width="100px">
              <el-input v-model="addForm.zaname" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="隧道编号" label-width="100px">
              <el-input v-model="addForm.sdid" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="隧道名称" label-width="100px">
              <el-input v-model="addForm.sdname" autocomplete="off"></el-input>
            </el-form-item>
            <!-- <el-form-item label="隧道编号" label-width="100px">
              <el-input v-model="addForm.sd_id" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="隧道名称" label-width="100px">
              <el-input v-model="addForm.sd_name" autocomplete="off"></el-input>
            </el-form-item> -->
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="支柱型号" label-width="100px">
              <el-input v-model="addForm.zztype" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="负责人" label-width="100px">
              <el-input
                v-model="addForm.directors"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公里标" label-width="100px">
              <el-input
                v-model="addForm.gonglibiao"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item label="跨距" label-width="100px">
              <el-input v-model="addForm.kuaju" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="概述" label-width="100px">
          <el-input
            type="textarea"
            v-model="addForm.overview"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注" label-width="100px">
          <el-input
            type="textarea"
            v-model="addForm.remark"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="
            currentOperation === 'add' ? handleAddConfirm : handleEditConfirm
          "
          >确认</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  selectAll,
  addNew,
  updateNew,
  deleteNew,
  downloadNew,
} from "@/api/gyjc/new";

export default {
  name: "GanhaoList",
  data() {
    return {
      loading: true,
      newList: [],
      allList: [], // 存储所有数据的列表
      currentPage: 1,
      pageSize: 10,
      total: 0,
      editDialogVisible: false,
      sortColumn: null, // 当前排序的列
      sortOrder: 1,
      addForm: {
        ganhaoid: null,
        ganhaoname: "",
        gq_id: null,
        zhanqu_id: null,
        zaname: "",
        sd_id: null,
        sd_name: "",
        zztype: "",
        directors: "",
        gonglibiao: "",
        kuaju: "",
        overview: "",
        remark: "",
      },
      currentOperation: "",
      dialogTitle: "新增杆号",
      searchKeyword: "",
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      selectAll()
        .then((response) => {
          this.allList = response.data;
          if (this.searchKeyword) {
            this.allList = this.allList.filter((item) => {
              return Object.values(item).some((value) =>
                String(value)
                  .toLowerCase()
                  .includes(this.searchKeyword.toLowerCase())
              );
            });
          }
          this.total = this.allList.length;
          this.newList = this.allList.slice(
            (this.currentPage - 1) * this.pageSize,
            this.currentPage * this.pageSize
          );
          this.loading = false;
        })
        .catch((error) => {
          console.error("接口请求出错:", error);
          this.loading = false;
        });
    },
    handleSort(prop) {
      if (this.sortColumn === prop) {
        console.log("切换排序方向前的 this.sortOrder 值：", this.sortOrder);
        this.sortOrder *= -1;
        console.log("切换排序方向后的 this.sortOrder 值：", this.sortOrder);
      } else {
        this.sortColumn = prop;
        this.sortOrder = 1;
      }
      this.allList.sort((a, b) => {
        if (a[prop] > b[prop]) return this.sortOrder;
        if (a[prop] < b[prop]) return -this.sortOrder;
        return 0;
      });
      this.newList = this.allList.slice(
        (this.currentPage - 1) * this.pageSize,
        this.currentPage * this.pageSize
      );
    },
    handleAdd() {
      this.editDialogVisible = true;
      this.dialogTitle = "新增杆号";
      this.addForm = {
        ganhaoid: null,
        ganhaoname: "",
        gqid: null,
        zhanquid: null,
        zaname: "",
        sdid: null,
        sdname: "",
        zztype: "",
        directors: "",
        gonglibiao: "",
        kuaju: "",
        overview: "",
        remark: "",
      };
      this.currentOperation = "add";
    },
    handleAddConfirm() {
      if (this.currentOperation === "add") {
        addNew(this.addForm)
          .then(() => {
            this.$message({
              type: "success",
              message: "添加成功!",
            });
            this.editDialogVisible = false;
            this.fetchData();
          })
          .catch((error) => {
            console.error("添加失败:", error);
            this.$message({
              type: "error",
              message: "添加失败",
            });
          });
      }
    },
    handleUpdate(row) {
      this.editDialogVisible = true;
      this.dialogTitle = "编辑杆号";
      this.addForm = { ...row };
      this.currentOperation = "edit";
    },
    handleEditConfirm() {
      if (this.currentOperation === "edit") {
        updateNew(this.addForm.ganhaoid, this.addForm)
          .then(() => {
            this.$message({
              type: "success",
              message: "更新成功!",
            });
            this.editDialogVisible = false;
            this.fetchData();
          })
          .catch((error) => {
            console.error("更新失败:", error);
            this.$message({
              type: "error",
              message: "更新失败",
            });
          });
      }
    },
    handleDelete(row) {
      this.$confirm("确认删除该记录吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteNew(row.ganhaoid)
            .then(() => {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.fetchData();
            })
            .catch((error) => {
              console.error("删除失败:", error);
              this.$message({
                type: "error",
                message: "删除失败",
              });
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleSelectionChange(val) {
      console.log(val);
    },
    handleDialogClose() {
      this.editDialogVisible = false;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.newList = this.allList.slice(
        (this.currentPage - 1) * this.pageSize,
        this.currentPage * this.pageSize
      );
    },
    handleDownload() {
      downloadNew()
        .then((response) => {
          const url = window.URL.createObjectURL(new Blob([response.data]));
          const link = document.createElement("a");
          link.href = url;
          link.setAttribute("download", "杆号数据.xlsx");
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        })
        .catch((error) => {
          console.error("下载失败:", error);
        });
    },
    handleSearch() {
      this.fetchData();
    },
  },
};
</script>